﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using TickSharp.Core.Infrastructure.Serializers;
using TickSharp.Core.Interfaces;
using TickSharp.Core.Interfaces.Repositories;
using TickSharp.Core.Model;

namespace TickSharp.Core.Infrastructure.Repositories
{
    public class EntryRepository : RepositoryBase, IEntryRepository
    {
        private readonly ISerializer<Entry> _serializer;

        private EntryRepository(IApiConnectionInfo apiConnectionInfo, ISerializer<Entry> serializer)
            : base(apiConnectionInfo)
        {
            _serializer = serializer;
        }

        public EntryRepository(IApiConnectionInfo apiConnectionInfo) : this(apiConnectionInfo, new EntrySerializer())
        {
        }

        /// <summary>
        /// Optional parameters:
        /// project_id
        /// task_id
        /// user_id
        /// user_email
        /// client_id
        /// entry_billable (true|false)
        /// billed (true|false)
        /// 
        /// Required Parameters:
        /// start_date AND end_date
        /// or
        /// updated_at
        /// </summary>
        /// <returns></returns>
        public IEnumerable<Entry> List(DateTime startDate, DateTime endDate, IEnumerable<EntryFilter> filters)
        {
            string additionalParameters =
                string.Format("start_date={0}&end_date={1}",
                    startDate.ToShortDateString(),
                    endDate.ToShortDateString()) +
                    FilterUrl(filters);

            string uri = BuildUrl("entries", additionalParameters);
            XElement elements = GetResponse(uri);
            return _serializer.Deserialize(elements);
        }

        public IEnumerable<Entry> List(DateTime startDate, DateTime endDate)
        {
            return List(startDate, endDate, new EntryFilter[] { });
        }

        public string FilterUrl(IEnumerable<EntryFilter> filters)
        {
            return string.Join("", filters.Select(filter => string.Format("&{0}={1}", filter.Type.ApiName, filter.Value)).ToArray());
        }
    }
}